import axios from 'axios'
import useUserStore from '@/stores/modules/user'
import { ElMessage, ElMessageBox } from 'element-plus'

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000, // request timeout
})

// request拦截器
service.interceptors.request.use(
  (config) => {
    // 延迟获取 userStore 实例，避免循环依赖问题
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers['Authorization'] = userStore.token // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  (error) => {
    console.log(error)
    Promise.reject(error)
  },
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.code !== 200) {
      if (res.code == 401) {
        ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          const userStore = useUserStore()
          userStore.userLogout().then(() => {
            location.reload()
          })
        })
      } else if (res.code == 500) {
        ElMessage({ message: res.message, type: 'error', duration: 2000 })
        return Promise.reject(res.data)
      } else {
        return Promise.reject(res.data)
      }
    } else {
      return res
    }
  },
  (error) => {
    console.log('err' + error)
    let { message } = error
    if (message == 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    ElMessage({ message: message, type: 'error', duration: 2000 })
    return Promise.reject(error)
  },
)

export default service
